﻿using MengRan.Models;
using MengRan.Models.bili;
using MengRan.Models.index;
using MengRan.Models.test;
using MengRan.Models.yuanshen;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MengRan.Controllers.api
{
    [ApiController]
    [Route("Home/api/[controller]/[action]")]
    public class chatController : Controller
    {
        private readonly MyDbContext _dbContext;
        public chatController(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        [HttpGet]
        public IActionResult chatmes(string use, string mes)
        {
            var a = "";
            using (_dbContext)
            {
                var chatq = new chatmes
                {
                    name = use,
                    mess = mes,
                    datatime = DateTime.Now
                };
                _dbContext.chatmess.Add(chatq);
                var i = _dbContext.SaveChanges();
                a = i > 0 ? "数据写入成功" : "数据写入失败";
            }
            return Ok(a);
        }
        [HttpGet]
        //a表示第几页评论
        public IActionResult Index(int a, string videoaid)
        {
            string ip = "https://api.bilibili.com/x/v2/reply/main?next=" + a + "&type=1&oid=" + videoaid + "&mode=3";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ip);
            WebResponse resp = req.GetResponse();
            StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default);
            string sReturn = sr.ReadToEnd().Trim();
            JObject result = JObject.Parse(sReturn);
            string data = result.Value<JToken>("data").ToString();
            JObject result2 = JObject.Parse(data);
            string replies = result2.Value<JToken>("replies").ToString();
            var list = JsonConvert.DeserializeObject<List<replies>>(replies);

            var aihei = list.Select(x => new qinglun
            {
                mid = x.member.mid,
                uname = x.member.uname,
                like = x.like,
                rcount = x.rcount,
                message = x.content.message,
                ctime = x.ctime
            });

            string jeiguo = JsonConvert.SerializeObject(aihei);


            List<qinglun> jsonq = JsonConvert.DeserializeObject<List<qinglun>>(jeiguo);

            return Ok(new { code = 0, count = jsonq.Count, data = jsonq, mes = "" });
        }
        [HttpGet]
        public IActionResult getall(string videoaid)
        {
            //
            int a = 1;
            string str = "";
            while (a < 1000)
            {
                string ip = "https://api.bilibili.com/x/v2/reply/main?next=" + a + "&type=1&oid=" + videoaid + "&mode=3";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ip);//http web 请求，Create：创造
                WebResponse resp = req.GetResponse();//GetResponse：获取响应
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default);//StreamReader：读，GetResponseStream：获取响应流
                string sReturn = sr.ReadToEnd().Trim();//读到尾
                JObject result = JObject.Parse(sReturn);//json Object解析
                string data = result.Value<JToken>("data").ToString();//取值
                JObject result2 = JObject.Parse(data);//再解析
                string replies = result2.Value<JToken>("replies").ToString();//再取值
                var list = JsonConvert.DeserializeObject<List<replies>>(replies);//取嵌套的值
                if (list == null) //不撞null不回头
                {
                    List<qinglun> jsonq = JsonConvert.DeserializeObject<List<qinglun>>("[" + str + "]");
                    return Ok(new { code = 0, count = jsonq.Count, data = jsonq, mes = "" });
                };
                var aihei = list.Select(x => new qinglun //循环取值
                {
                    mid = x.member.mid,
                    uname = x.member.uname,
                    like = x.like,
                    rcount = x.rcount,
                    message = x.content.message,
                    ctime = x.ctime
                });
                //下面这一段存库就用，单纯查数据就注释掉
                List<qinglun> logDate = new List<qinglun>();
                foreach (var item in list)
                {
                    logDate.Add(new qinglun
                    {
                        mid = item.member.mid,
                        uname = item.member.uname,
                        like = item.like,
                        rcount = item.rcount,
                        message = item.content.message,
                        ctime = item.ctime
                    });
                }
                _dbContext.bilimes.AddRange(logDate);
                var i = _dbContext.SaveChanges();
                string message = i > 0 ? "添加成功" : "添加失败";
                string jeiguo = JsonConvert.SerializeObject(aihei);//转string
                var datasw = jeiguo.TrimStart("[".ToCharArray()).TrimEnd("]".ToCharArray());//去头去尾
                str += datasw.ToString() + ",";//拼接多个数组
                a++;
            }
            return Ok();
        }
        [HttpGet]
        public IActionResult chouka(string we, string leixing)
        {
            
            string endid = "0";
            string str = "";

            while (endid != "")
            {
                //we = we.Replace("https://webstatic.mihoyo.com/hk4e/event/e20190909gacha/index.html?", "https://hk4e-api.mihoyo.com/event/gacha_info/api/getGachaLog?");
                if (endid != "0")
                {
                    we = we.Substring(0, we.IndexOf("&gacha_type="));
                }
                we = we + "&gacha_type=" + leixing + "&page=1&size=20&end_id=" + endid + "";
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(we);
                WebResponse resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.Default);
                string sReturn = sr.ReadToEnd().Trim();
                JObject result = JObject.Parse(sReturn);
                string data = result.Value<JToken>("data").ToString();
                JObject result2 = JObject.Parse(data);
                string replies = result2.Value<JToken>("list").ToString();
                if (replies == "[]")
                {
                    List<choukashuju> jsonq = JsonConvert.DeserializeObject<List<choukashuju>>("[" + str + "]");
                    return Ok(new { code = 0, count = jsonq.Count, data = jsonq, mes = "" });
                }
                List<choukashuju> ws = JsonConvert.DeserializeObject<List<choukashuju>>(replies);
                foreach (var item in ws)
                {
                    endid = item.id;
                }
                var datasw = replies.TrimStart("[".ToCharArray()).TrimEnd("]".ToCharArray());//去头去尾
                str += datasw.ToString() + ",";//拼接多个数组
                Thread.Sleep(300);
            }
            return Ok();
        }
    }
}
